import {messages,queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import ExportModal from 'components/template/export-modal/export-modal';
import { Button, Popover, message,Row,Col,Icon,Modal } from 'antd';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import menuRoute from 'routes/menuRoute'
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import common  from'containers/financial-management/check-center/check-common'
import 'styles/setting/wait-for-billing/billing-detail.scss'
import ResizeTable from 'components/resize-table'
import moment from 'moment'

class BillingDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 0,
      size: 10,
      loading: false,
      data: [],
      receiptedData:{},
      pagination: {
        total: 0
      },
      copied:false,
      showIdCard:false,
      cardInfo:{},
      defaultAddressInfo:{},
      receiptedInvoiceDetail:{
        "invoiceTypeResp":{}
      },
      searchParams: {},
      personCorporationEntityList: [],//按个人信息 法人实体
      expenseCorporationEntityList: [],//按单据信息 法人实体
      personDepartmentList: [],//按个人信息 部门
      expenseDepartmentList: [],//按单据信息 部门
      costCenterList: [],//按单据信息 成本中心
      columns: [
        {title: messages('financial-management.key403'/*序号*/), dataIndex: 'index', width: 48},
        {title: messages('financial-management.key377'/*姓名*/), dataIndex: 'userName',width:'10%',render:this.renderIdCard},
        {title: messages('financial-management.key404'/*日期*/), dataIndex: 'createdDate',width: 120,render:createdDate => <span>{moment(createdDate).format('YYYY-MM-DD')}</span>},
        {title: messages('financial-management.key405'/*币种*/), dataIndex: 'currency',width:48,render:() => <span>{this.props.companyConfiguration.currencyCode}</span>},
        {title: messages('financial-management.key406'/*金额*/), dataIndex: 'orderAmount',width:'8%',align:'right', render:(value) => this.filterMoney(value,queryCurrencyPrecision())},
        {title: messages('financial-management.key407'/*付款状态*/), dataIndex: 'paymentState',width:'10%', render: paymentState => paymentState === 1001 ? messages('financial-management.key408'/*未付款*/) : messages('financial-management.key409'/*已付款*/)},
        {title: messages('financial-management.key410'/*支付方式*/), dataIndex: 'paymentType',width:'10%',render:paymentType =>paymentType === 1001 ? messages('financial-management.key411'/*个人垫付*/) : messages('financial-management.key412'/*公司垫付*/)},
        {title: messages('financial-management.key413'/*开票状态*/), dataIndex: 'invoiceStateInfo',width:'8%',render:this.renderStateInfo},
        {title: messages('financial-management.key414'/*说明*/), dataIndex: 'failReason',width:'18%',render:this.renderReasonInfo}
      ],
      billingType: props.params.billingType,
    };
    this.menuBilling = menuRoute.getRouteItem('wait-for-billing-list');
  }

  componentWillMount(){
    this.getList();
  }

  //渲染人员卡片
  renderIdCard =(value,record) =>{
   return <span style={{cursor:"pointer"}}  onClick={()=>this.operateIdCard(true,record)} >{record.userName}<Icon type="idcard" style={{marginLeft:'10px'}}/></span>
  };

  operateIdCard = (flag,record)=>{
    this.setState({showIdCard:flag,cardInfo:record})
  };

  handleCancelModal =()=>{
    this.setState({showIdCard:false})
  };

  renderReasonInfo = (value,record) =>{
    let reason = '';
    record.receiptedStatus === 1 ? reason = '-' : reason = value;
    return reason;
  };

  renderStateInfo = (value,record) =>{
    if(record.receiptedStatus ===1){
      return <span>{messages('financial-management.key415'/*成功*/)}</span>
    }else if(record.receiptedStatus === 2 ){
      return <span>{messages('financial-management.key416'/*失败*/)}</span>
    } else if(record.paymentState === 0){
      return <span>{messages('financial-management.key417'/*异常*/)}</span>
    }
  };

  getList(){
    const { page, size, searchParams } = this.state;
    searchParams.page = page;
    searchParams.size = size;
    searchParams.receiptedInvoiceOid=this.props.params.receiptedInvoiceOID;
    let param={
      receiptedInvoiceOid:this.props.params.receiptedInvoiceOID
    };
    this.setState({ loading: true }, () => {
      Promise.all([
        BillingService.getCompanyReceiptedInvoicesDetail(param),
        BillingService.getCompanyReceiptedInvoicesByPage(searchParams)
      ]).then(res => {
        let detailData = res[1].data;
        let tableData = detailData.rows;
        if(tableData.length>0){
          tableData.map((item ,index) => {
            item.index = index + size * page + 1;
            item.currency = 'CNY';
            return item;
          });
        }else{
          tableData =[]
        }
        this.setState({
          receiptedInvoiceDetail: res[0].data,
          loading: false,
          data: tableData,
          pagination: {
            total: detailData.total,
            onChange: this.onChangePager,
            current: page + 1
          }
        })
      });
    });
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  refreshStatus = ()=>{
    this.getList()
  }

  //重新开票
  reApplyForReceiptedInvoice = ()=>{
    BillingService.reApplyForReceiptedInvoice(this.props.params.receiptedInvoiceOID).then(res =>{
      if(res.status === 200){
        message.success(messages('financial-management.key420'/*申请重新开票成功*/))
        this.getList()
      }
    }).catch((e)=>{
      message.error(messages('financial-management.key421'/*申请重新开票失败*/))
    })
  };

  onCopy = () => {
    this.setState({copied: true});
  };
  onClickCopy = () =>{
    message.success(messages('financial-management.key422'/*复制成功*/));
  }

  goBack = () => {
    this.context.router.push(this.menuBilling.url.replace(':billingType',this.state.billingType))
  };
  //转成数组值
  transArray = (obj,attrName,valueName) =>{
    let array=[];
    if(obj && attrName && obj[attrName]){
      obj[attrName].map(item=>{
        array.push(item[valueName])
      })
    }
    return array;
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType){
      case 'DIDI':
        result = messages('financial-management.key423'/*滴滴账户*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key548'/*甄选账号*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key549'/*神州账户*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };


  render(){

    const {data, pagination, columns, loading, showIdCard, cardInfo, billingType, receiptedInvoiceDetail} = this.state;
    let costCentersName = this.transArray(receiptedInvoiceDetail, 'costCenters', 'entityName');
    let personSearchLegalEntitiesName = this.transArray(receiptedInvoiceDetail, 'personSearchLegalEntities', 'entityName');
    let personSearchDepartmentsName = this.transArray(receiptedInvoiceDetail, 'personSearchDepartments', 'entityName');
    let expenseSearchLegalEntitiesName = this.transArray(receiptedInvoiceDetail, 'expenseSearchLegalEntities', 'entityName');
    let expenseSearchDepartmentsName = this.transArray(receiptedInvoiceDetail, 'expenseSearchDepartments', 'entityName');
    return (
      <div className="billing-detail">
        <Row className='detail-info'>
          <Col span={2}>{messages('financial-management.key426'/*申请ID*/)}：</Col><Col span={6}>{receiptedInvoiceDetail.applicantID}</Col>
          <Col span={2}>{messages('financial-management.key427'/*申请日期*/)}：</Col><Col span={6}>{moment(receiptedInvoiceDetail.createdDate).format('YYYY-MM-DD HH:mm:ss')}</Col>
          <Col span={2}>{messages('financial-management.key428'/*开票抬头*/)}</Col><Col span={6}>{receiptedInvoiceDetail.title}</Col>
        </Row>
        <Row className='detail-info'>
          <Col span={2}>{messages('financial-management.key429'/*日期范围*/)}：</Col><Col span={6}><span>{`${moment(receiptedInvoiceDetail.startDate).format('YYYY-MM')}`}</span></Col>
          
          <Col span={2}>{messages('financial-management.key433'/*开票类型*/)}</Col><Col span={6}>{receiptedInvoiceDetail.invoiceTypeResp?receiptedInvoiceDetail.invoiceTypeResp.name:""}</Col>
        </Row>
        <Row className='detail-info'>
          <Col span={3}>{messages('financial-management.key434'/*单据信息法人*/)}：</Col><Col span={5}>{!receiptedInvoiceDetail.expenseSearchLegalEntities ? <span>{messages('financial-management.key432'/*全部*/)}</span> :
          <div className='line-clamp'><Popover content={expenseSearchLegalEntitiesName.join('、')}>{expenseSearchLegalEntitiesName.join('、')}</Popover></div>}
        </Col>
          {
            billingType!='CLOUD_HELIOS_HOTEL' && (
              <Col>
                <Col span={2}>{this.renderBillingType()}：</Col>
                <Col span={6}>{receiptedInvoiceDetail.vendorAccountName}</Col>
              </Col>
            )
          }
        </Row>
        {
          receiptedInvoiceDetail.bankCardType&& receiptedInvoiceDetail.bankCardType.entityName && (
            <Row className='detail-info'>
              <Col span={2}>{messages('financial-management.key436'/*商务卡支付*/)}：</Col>
              <Col span={6}>{receiptedInvoiceDetail.bankCardType.entityName}</Col>
            </Row>
          )
        }
        <Row className='detail-info'>
          <Col span={2}>{messages(~['ELECTRONICORDINARY'].indexOf(receiptedInvoiceDetail.invoiceTypeResp.type) ?'financial-management.key473':'financial-management.key475')}：</Col>
          {!~['ELECTRONICORDINARY'].indexOf(receiptedInvoiceDetail.invoiceTypeResp.type)&&receiptedInvoiceDetail.receiverDTO&&<Col span={22}>{receiptedInvoiceDetail.receiverDTO.receiverAddress}
            &nbsp;&nbsp;{receiptedInvoiceDetail.receiverDTO.receiverZipCode}
            &nbsp;&nbsp;{receiptedInvoiceDetail.receiverDTO.receiverName}
            &nbsp;&nbsp;{receiptedInvoiceDetail.receiverDTO.receiverPhone}
          </Col>}
          {~['ELECTRONICORDINARY'].indexOf(receiptedInvoiceDetail.invoiceTypeResp.type) && <Col span={6}>{receiptedInvoiceDetail.email}</Col>}
        </Row>
        <div className='total-message'>
          {(receiptedInvoiceDetail.receiptingCount !== 0) && <Button type='primary' onClick={this.refreshStatus}>{messages('financial-management.key437'/*刷新开票状态*/)}</Button>}
          {(receiptedInvoiceDetail.receiptingCount === 0) &&
            <ExportModal type={"btn"}
                         exportTitle={messages('financial-management.key438'/*导出订单明细*/)}
                         exportType="VENDOR_RECEIPTED_TYPE"
                         exportCondition={{
                           receiptedInvoiceOid: this.props.params.receiptedInvoiceOID
                         }}
            exportCommand={'VENDOR_RECEIPTED_TYPE'}/>
          }
          <Button style={{marginLeft:'10px'}} onClick={this.goBack}>{messages('financial-management.key439'/*返回*/)}</Button>
          {(receiptedInvoiceDetail.totalCount !== receiptedInvoiceDetail.successCount) && <div className='detail-num'>
            <span>{messages('financial-management.key550',{arg1:receiptedInvoiceDetail.totalCount}/*共计{arg1}条费用*/)},</span>
            <span>{messages('financial-management.key551',{arg1:receiptedInvoiceDetail.successCount}/*成功处理{arg1}条费用*/)}</span>
          </div>}
          {(receiptedInvoiceDetail.totalCount  === receiptedInvoiceDetail.successCount) && <div className='invoice-done'>{messages('financial-management.key440'/*开票完成*/)}！</div>}
          {(receiptedInvoiceDetail.receiptedInvoiceStatus !== 1007 && receiptedInvoiceDetail.receiptedInvoiceStatus !== 1001 && !loading ) && <Button type='primary' onClick={this.reApplyForReceiptedInvoice}>{messages('financial-management.key441'/*重新开票*/)}</Button>}
        </div>
        {/*按订单开票*/}
        {(receiptedInvoiceDetail.invoiceApplyInfo && (receiptedInvoiceDetail.invoiceApplyInfo.personal.failedCount > 0 || receiptedInvoiceDetail.invoiceApplyInfo.personal.successCount > 0))
        &&
        <div className='table-message'>
          <Icon type="database" className='personal-icon'/>
          <div>{messages('financial-management.key442'/*按订单开票*/)}</div>
          {(receiptedInvoiceDetail.invoiceApplyInfo && receiptedInvoiceDetail.invoiceApplyInfo.personal.successCount) &&
          <div className='message-status'>
            <span>{messages('financial-management.key443'/*开票成功*/)}</span>
            <span className='success-number'>{receiptedInvoiceDetail.invoiceApplyInfo.personal.successCount}</span>
            <span>{messages('financial-management.key444'/*条费用,总计金额*/)}</span>
            <span className='success-money'>{this.props.companyConfiguration.currencyCode}{common.formatCurrency(receiptedInvoiceDetail.invoiceApplyInfo.personal.successAmount)}</span>
          </div>}
          {(receiptedInvoiceDetail.invoiceApplyInfo && receiptedInvoiceDetail.invoiceApplyInfo.personal.failedCount > 0) &&
          <div className='message-status'>
            <span className='fail-title'>{messages('financial-management.key445'/*开票失败*/)}</span>
            <span className='error-number'>{receiptedInvoiceDetail.invoiceApplyInfo.personal.failedCount}</span>
            <span>{messages('financial-management.key444'/*条费用,总计金额*/)}</span>
            <span className='success-money'>{this.props.companyConfiguration.currencyCode}{common.formatCurrency(receiptedInvoiceDetail.invoiceApplyInfo.personal.failedAmount)}</span>
          </div>

          }
        </div>}

        {/*按企业充值*/}
        {(receiptedInvoiceDetail.invoiceApplyInfo && (receiptedInvoiceDetail.invoiceApplyInfo.business.failedCount > 0 || receiptedInvoiceDetail.invoiceApplyInfo.business.successCount > 0))
        &&
        <div className='table-message'>
          <Icon type="exception" className='business-icon'/>
          <div>{messages('financial-management.key446'/*按企业充值*/)}</div>
          {(receiptedInvoiceDetail.invoiceApplyInfo && receiptedInvoiceDetail.invoiceApplyInfo.business.successCount) &&
          <div className='message-status'>
            <span>{messages('financial-management.key443'/*开票成功*/)}</span>
            <span className='success-number'>{receiptedInvoiceDetail.invoiceApplyInfo.business.successCount}</span>
            <span>{messages('financial-management.key444'/*条费用,总计金额*/)}</span>
            <span className='success-money'>{this.props.companyConfiguration.currencyCode}{common.formatCurrency(receiptedInvoiceDetail.invoiceApplyInfo.business.successAmount)}</span>
          </div>}
          {(receiptedInvoiceDetail.invoiceApplyInfo && receiptedInvoiceDetail.invoiceApplyInfo.business.failedCount > 0) &&
          <div className='message-status'>
            <span className='fail-title'>{messages('financial-management.key445'/*开票失败*/)}</span>
            <span className='error-number'>{receiptedInvoiceDetail.invoiceApplyInfo.business.failedCount}</span>
            <span>{messages('financial-management.key444'/*条费用,总计金额*/)}</span>
            <span className='success-money'>{this.props.companyConfiguration.currencyCode}{common.formatCurrency(receiptedInvoiceDetail.invoiceApplyInfo.business.failedAmount)}</span>
          </div>

          }
        </div>}
        <Modal visible={showIdCard} footer={null} onCancel={this.handleCancelModal}>
          <div>{messages('financial-management.key447'/*分公司*/)}：{cardInfo.companyName}</div>
          <div>{messages('financial-management.key448'/*部门*/)}：{cardInfo.departmentName}</div>
          <div>{messages('financial-management.key449'/*报销单号*/)}：{cardInfo.parentBusinessCode}{cardInfo.subBusinessCode && <span>-{cardInfo.subBusinessCode}</span>}</div>
          {cardInfo.parentBusinessCode ?
            <CopyToClipboard
              onCopy={this.onCopy}
              text={cardInfo.parentBusinessCode}>
              <div style={{textAlign:'right'}}><Button type='primary'  onClick={this.onClickCopy}>{messages('financial-management.key450'/*复制单号*/)}</Button></div>
            </CopyToClipboard>
            :
            <CopyToClipboard
              onCopy={this.onCopy}
              text={cardInfo.subBusinessCode}>
              <div style={{textAlign:'right'}}><Button type='primary'  onClick={this.onClickCopy}>{messages('financial-management.key451'/*复制子单号*/)}</Button></div>
            </CopyToClipboard>
          }
        </Modal>
        <ResizeTable
          columns={columns}
          bordered
          pagination={pagination}
          loading={loading}
          rowKey="invoiceOid"
          dataSource={data}
          size="middle"
        />
      </div>
    )
  }

}

BillingDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    companyConfiguration: state.login.companyConfiguration,
    company: state.login.company,
    profile: state.login.profile,
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(BillingDetail);
